/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package se392.ateam2006.authentication;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import se392.ateam2006.user.UserEntity;
import se392.ateam2006.user.UserMgmtLocal;

/**
 *
 * @author Caroline
 */
@Stateless
public class GroupMgmtBean implements Serializable, GroupMgmtRemote, GroupMgmtLocal {

    // Add business logic below. (Right-click in editor and choose
    // "EJB Methods > Add Business Method" or "Web Service > Add Operation")
    @PersistenceContext
    private EntityManager em;
    
    @EJB
    private UserMgmtLocal userManage;

    public GroupMgmtBean() {

    }

    public boolean addGroup(String groupid) {
        GroupEntity group = em.find(GroupEntity.class, groupid);
        if (group == null) {
            GroupEntity ge = new GroupEntity(groupid);
            em.persist(ge);
            return true;
        }
        return false;

    }

    public boolean removeGroup(String groupid) {
        GroupEntity group = em.find(GroupEntity.class, groupid);
        if (group != null) {
            List<UserEntity> users = group.getUsers();
            for (UserEntity ue : users) {
                ue.removePermission(groupid);
            }
            group.removeAllUsers();
            em.remove(group);
            return true;
        }
        return false;
    }

    public boolean addUserToGroup(String groupid, String userid) {
        try {
        GroupEntity group = em.find(GroupEntity.class, groupid);
        UserEntity user = userManage.getUserByID(userid);
        if(group != null && user != null) {
            group.addUser(user);
            //user.addPermission(group);
            return true;
        }
        }catch(Exception e) {
            System.err.println("CAZ: adduserTogroup " + e.getMessage());
        }
        return false;
    }
    
    public GroupEntity getGroupById(String permission) {
        return em.find(GroupEntity.class, permission);
    }
    

    public boolean removeUserFromGroup(String groupid, UserEntity user) {
        GroupEntity group = em.find(GroupEntity.class, groupid);
        if(group != null) {
            group.removeUser(user);
            return true;
        }
        return false;
    }
    
    public Collection<GroupEntity> getAllGroups() {
         Query q = em.createQuery("Select g from GroupEntity g ");
         return q.getResultList();
    }
}
